//
//  DownUpGestureRecognizer.swift
//  Demo-10 自定义手势+指定区域识别触摸
//
//  Created by quanhao huang on 2019/10/8.
//  Copyright © 2019 demo. All rights reserved.
//

import UIKit

class DownUpGestureRecognizer: UIGestureRecognizer {

    //手势分为两部分，先下移随后上移
    enum DownUpGesturePhase {
        case MovingDown, MovingUp
        
        var description:String{
            get {
                switch self {
                case .MovingDown:
                    return "Moving Down"
                case .MovingUp:
                    return "Moving Up"
                }
            }
        }
    }
    
    var phase : DownUpGesturePhase = .MovingDown
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
        self.phase = .MovingDown
        if self.numberOfTouches > 1 {
            //toouch>1则不是需要的手势，标记为.failed
            self.state = .failed
        }else {
            //否则可能为下滑手势，标记为.possible
            self.state = .possible
        }
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
        let touch = touches.first
        
        //获取触摸的位置和上一个位置
        let position = touch?.location(in: touch?.view)
        let lastPosition = touch?.previousLocation(in: touch?.view)
        
        //状态为.possible时侦测手势开始
        if self.state == .possible {
            if position!.y > lastPosition!.y {
                self.state = .began
            }
        }
        
        if self.state == .began || self.state  == .changed {
            //如果手势仍处于下滑状态，并开始向上移动则记录为.changed
            self.state = .changed
        }
        
        //如果在触摸结束时，下移则判断为失败
        if self.phase == .MovingUp && position!.y > lastPosition!.y {
            self.state = .failed
        }
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
        // 如果触摸结束下移，则也判定失败
        if self.phase == .MovingDown {
            self.state = .failed
        }else if self.phase == .MovingUp {
            self.state = .ended
        }
    }
}
